package com.dushiguang.findhoney.View.Banner;

import android.os.Looper;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;


/**
 * Created by ex-dushiguang201 on 2015-11-30.
 */
public class BannerHandler extends ViewPager.SimpleOnPageChangeListener {


    private boolean mRunning;
    private long mSwitchDlay = 3000L;//滚动事件

    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                final int currentItem = mViewPager.getCurrentItem();
                mViewPager.setCurrentItem(currentItem < mViewPager.getAdapter().getCount() - 1 ? currentItem + 1 : 0);
            }
        }
    };

    private final ViewPager mViewPager;

    public BannerHandler(ViewPager viewPager, long... switchDelay) {
        if(Looper.myLooper() != Looper.getMainLooper()) {
            throw new IllegalStateException("Do not use BannerHandler out of main looper.");
        }

        if (viewPager == null) {
            throw new NullPointerException("Did you forget initialize ViewPager?");
        }

        if (viewPager.getAdapter() == null) {
            throw new IllegalArgumentException("Did you forget set an adapter for ViewPager?");
        }

        mViewPager = viewPager;
    }

    public BannerHandler start() {
        if (!mRunning) {
            mRunning = true;
            sendMessage(mSwitchDlay);
        }

        return this;
    }

    public BannerHandler stop() {
        removeMessage();
        mRunning = false;
        return this;
    }

    public BannerHandler setSwitchDelay(long switchDelay) {
        mSwitchDlay = switchDelay;
        return this;
    }

    @Override
    public void onPageSelected(int position) {
        sendMessage(mSwitchDlay);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (state == ViewPager.SCROLL_STATE_DRAGGING) {
            removeMessage();
        } else if (state == ViewPager.SCROLL_STATE_IDLE) {
            sendMessage(mSwitchDlay);
        }
    }

    private void sendMessage(long delay) {
        if (mRunning) {
            removeMessage();
            mHandler.sendEmptyMessageDelayed(0, delay);
        }
    }

    private void removeMessage() {
        mHandler.removeMessages(0);
    }
}
